package com.liush.bookstore.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/*
* 验证码图片控制层
* */
@RestController
public class ImageController {

    @Qualifier("kapcha")
    @Autowired
    private Producer producer;

    @GetMapping("/img")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) {
        response.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("code", text);
        BufferedImage image = producer.createImage(text);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}